class Sanke {
    // 蛇头
    head : HTMLElement;
    // 身体 （包含蛇头）
    bodies : HTMLCollection;
    // 获取蛇的容器
    element : HTMLElement;
    constructor() {
        this.element = document.getElementById('snake')!
        this.head = document.querySelector('#snake > div')!
        this.bodies = this.element.getElementsByTagName('div')
        
    }

    // 获取蛇的坐标
    get location(){
        // 蛇头的坐标
        let location = {
            x : this.head.offsetLeft,
            y : this.head.offsetTop
        }
        return location;
    }

    set X (val:number){
        if(this.location.x === val){
            return
        }
        if(val < 0 || val > 290){
            throw new Error('蛇撞墙了')
        }
        if(this.bodies[1] && ((this.bodies[1] as HTMLElement).offsetLeft === val)){
            if(val > this.location.x){
                val = this.location.x - 10
            }else{
                val = this.location.x + 10
            }
        }
        this.moveBody()
        this.head.style.left = val + 'px';
        this.checkHeadBody()
    }
    set Y (val:number){
        if(this.location.y === val){
            return
        }
        if(val < 0 || val > 290){
            throw new Error('蛇撞墙了')
        }
        if(this.bodies[1] && ((this.bodies[1] as HTMLElement).offsetTop === val)){
            if(val > this.location.y){
                val = this.location.y - 10
            }else{
                val = this.location.y + 10
            }
        }
        this.moveBody()
        this.head.style.top = val + 'px';
        this.checkHeadBody()

    }
    // 添加身体
    addBody(){
        this.element.insertAdjacentHTML('beforeend','<div></div>')
    }
    // 移动身体
    moveBody(){
        for(let i = this.bodies.length-1;i>0;i--){
            let x = (this.bodies[i-1] as HTMLElement).offsetLeft;
            let y = (this.bodies[i-1] as HTMLElement).offsetTop;
            (this.bodies[i] as HTMLElement).style.left = x + 'px';
            (this.bodies[i] as HTMLElement).style.top = y + 'px';
        }
    }
    // 检查头部是否撞到身体
    checkHeadBody(){
        for(let i = 1;i<this.bodies.length;i++){
            let bd = this.bodies[i] as HTMLElement;
            if(this.location.x === bd.offsetLeft && this.location.y === bd.offsetTop){
                throw new Error('撞到自己了')
            }
        }
    }
}

export default Sanke;


/*
一切众生
未解脱者
性识无定
恶习结业
善习结果
为善为恶
逐境而生
轮转五道
暂无休息
动经尘劫
迷惑障难
如鱼游网
将是长流
脱入暂出
又复遭网
以是等辈
吾当忧念
汝既毕是往愿
累劫重誓
广度罪辈
吾复何虑

*/ 